<template>
  <canvas
    class="webgl"
    id="canvas"
    ref="rotate"
    width="500"
    height="600"
  ></canvas>
</template>

<script>
import * as THREE from "three";

export default {
  props: {
    angleDataY: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      cube: null,
    };
  },
  watch: {
    angleDataY(newVal) {
      this.renderLoop(newVal);
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      const canvas = document.querySelector("canvas.webgl");

      const sizes = {
        width: 500,
        height: 600,
      };

      this.scene = new THREE.Scene();
      this.scene.background = new THREE.Color(0xc0c0c0);

      const cubeGeometry = new THREE.BoxGeometry(0.8, 3, 0.2); //创建一个立方体几何对象
      const cubeMaterial = new THREE.MeshLambertMaterial({
        color: 0x696969,
      });

      this.cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
      this.scene.add(this.cube); //添加立方体对象到场景

      this.camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height); // 透视相机
      this.camera.position.z = 3;
      this.scene.add(this.camera); //添加相机到场景

      const light = new THREE.DirectionalLight(0xffffff, 1);
      light.intensity = 1;
      light.position.set(18, 20, 60);
      light.castShadow = true;
      light.target = this.cube;
      light.shadow.mapSize.width = 512 * 12;
      light.shadow.mapSize.height = 512 * 12;
      light.shadow.camera.top = 80;
      light.shadow.camera.bottom = -80;
      light.shadow.camera.left = -80;
      light.shadow.camera.right = 80;
      this.scene.add(light);
      const ambientLight = new THREE.AmbientLight(0xffffff);
      ambientLight.intensity = 0.8;
      this.scene.add(ambientLight);
      const hemisphereLight = new THREE.HemisphereLight(0xffffff, 0xfffc00);
      hemisphereLight.intensity = 0.3;
      this.scene.add(hemisphereLight);

      const grid = new THREE.GridHelper(200, 200, 0xffffff, 0xffffff);
      grid.position.set(0, -30, -50);
      grid.material.transparent = true;
      grid.material.opacity = 0.1;
      this.scene.add(grid);

      var planeGeometry = new THREE.PlaneGeometry(200, 200);
      var planeMaterial = new THREE.ShadowMaterial({ opacity: 0.5 });
      var plane = new THREE.Mesh(planeGeometry, planeMaterial);
      plane.rotation.x = -0.5 * Math.PI;
      plane.position.set(0, -30, -50);
      plane.receiveShadow = true;
      this.scene.add(plane);

      this.renderer = new THREE.WebGLRenderer({ canvas: canvas });
      this.renderer.setSize(sizes.width, sizes.height);
      this.renderer.render(this.scene, this.camera);
    },

    renderLoop(angleDataY) {
      if(this.cube){
        this.cube.rotation.y = (angleDataY * Math.PI) / 180;
        this.renderer.render(this.scene, this.camera);
      }
    },
  },
};
</script>
